<template>
	<view class="u-p-l-40 u-p-r-40">
		<u-form :model="form" ref="uForm">
			<u-form-item label="昵称" prop="name">
				<u-input v-model="form.name" placeholder="请输入昵称" />
			</u-form-item>
		</u-form>
		<u-button @click="submit" type="primary">提交</u-button>
	</view>
</template>

<script>
	import {
		upadateUser,
		getUser
	} from "../../common/http.api.js"
	export default {
		data() {
			return {
				form: {
					name:""
				},
				rules: {
					name: [{
						required: true,
						message: '请输入昵称',
						// 可以单个或者同时写两个触发验证方式 
						trigger: "blur",
					}],
				}
			};
		},
		onLoad() {
			this.form['name'] = JSON.parse(uni.getStorageSync('UserInfo')).userInfo.name;
		},
		methods: {
			submit() {
				this.$refs.uForm.validate(valid => {
					uni.showLoading({
						title: "提交中"
					})
					if (valid) {
						this.$u.api.upadateUser({
							name: this.form.name
						}).then(res => {
							this.$u.api.getUser().then(res1 => {
								this.$store.dispatch('asynUser', res1.data);
								uni.hideLoading();
								setTimeout(() => {
									uni.reLaunch({
										url: "/pages/my/my"
									})
								}, 500)
							})

						})
					} else {
						uni.hideLoading();
					}
				});
			}
		},
		// 必须要在onReady生命周期，因为onLoad生命周期组件可能尚未创建完毕
		onReady() {
			this.$refs.uForm.setRules(this.rules);
		}
	};
</script>
